#!/bin/bash

set -euo pipefail

handle_bazel_exit() {
  exit_code=$?
  case $exit_code in
    0) ;;
    # Ignore BES failures
    38|45) ;;
    *) exit $exit_code ;;
  esac
}

readonly tool_location="${BASH_SOURCE[0]}"
readonly workspace_dir="${tool_location%/*/*}"

bazel_version=$("$BAZEL_REAL" info release | /usr/bin/cut -d ' ' -f 2 | /usr/bin/cut -d '.' -f 1)
if [[ "$bazel_version" == "version" ]]; then
  bazel_version=8
fi

flags=("--noworkspace_rc")

readonly workspace_version_bazelrc="$workspace_dir/bazel_$bazel_version.bazelrc"
if [[ -s "$workspace_version_bazelrc" ]]; then
  flags+=("--bazelrc=$workspace_version_bazelrc")
fi

readonly workspace_bazelrc="$workspace_dir/.bazelrc"
if [[ -s "$workspace_bazelrc" ]]; then
  flags+=("--bazelrc=$workspace_bazelrc")
fi

"$BAZEL_REAL" "${flags[@]}" "$@" || handle_bazel_exit
